package dormouse.vfs.ui.renderers;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

import org.apache.commons.vfs2.FileObject;

/**
 * This class is responsible for creating file renderers.
 *
 * @param <C> the file renderer component.
 * @see IFileRenderer
 */
public class FileRendererFactory {

    /**
     * A map containing all renderers, whose keys are the extensions supported
     * by the renderer.
     */
    static Map<String, IFileRenderer> extensionMap = new HashMap<String, IFileRenderer>();
    static Map<String, IFileRenderer> rendererMap = new HashMap<String, IFileRenderer>();
    

    static {

    	ServiceLoader<IFileRenderer> loader = ServiceLoader.load(IFileRenderer.class);
        Iterator<IFileRenderer> fileRendererIt = loader.iterator();
        IFileRenderer currRenderer = null;
        String[] exts = null;

        while (fileRendererIt.hasNext()) {
            currRenderer = fileRendererIt.next();
            rendererMap.put(currRenderer.toString(), currRenderer);
            exts = currRenderer.getFileExtensions();

            if (exts != null) {
                for (int i = 0; i < exts.length; i++) {
                    extensionMap.put(exts[i].toLowerCase(), currRenderer);
                }
            }
        }

    }

    /**
     * This method is responsible for getting an instance of the IFileRenderer
     * appropriate for the given file extension.  If the file extension is
     * not supported, then the 
     * @param file	The file object
     * @return the renderer for the specific file.
     */
    public static IFileRenderer getInstance(FileObject file) {
        return extensionMap.get(file.getName().getExtension().toLowerCase());
    }
}
